package models

import (
	"context"
	"go-chain-data/global"
	"go.mongodb.org/mongo-driver/bson"
	"log"
)

type WatchAddressInfo struct {
	ChainName      string `bson:"chainName"`
	ChainId        uint   `bson:"chainId"`
	BlockNumber    uint64 `bson:"blockNumber"`
	TxHash         string `bson:"txHash"`
	From           string `bson:"from"`
	To             string `bson:"to"`
	Token          string `bson:"token"`
	Amount         string `bson:"amount"`
	Verify         int64  `bson:"verify"`
	CallBackUrl    string `bson:"callBackUrl"`    // 回调地址
	CallBackTime   int64  `bson:"callBackTime"`   // 下次回调时间
	CallBackResult string `bson:"callBackResult"` // 回调返回数据
	CallBackNumber int64  `bson:"callBackNumber"` // 回调次数
}

// InsertWatchAddressInfo 插入数据
func InsertWatchAddressInfo(watchAddressInfo WatchAddressInfo) error {
	WatchAddressInfoClient := global.DBEngine.Database(global.DbConfig.DbName).Collection("watch_address_info")
	_, err := WatchAddressInfoClient.InsertOne(context.Background(), watchAddressInfo)
	if err != nil {
		return err
	}
	return nil
}

// DeleteByBlockNumber 根据区块高度删除数据
func (watchAddressInfo WatchAddressInfo) DeleteByBlockNumber(blockNumber int64) error {
	filter := bson.D{
		{"blockNumber", bson.D{{"$gt", blockNumber}}},
		{"chainName", global.BlockChainConfig.Name},
		{"chainId", global.BlockChainConfig.Id},
	}
	// 删除watch_address_info表
	watchClient := global.DBEngine.Database(global.DbConfig.DbName).Collection("watch_address_info")
	_, err3 := watchClient.DeleteMany(context.Background(), filter)
	if err3 != nil {
		log.Println("删除watch_address_info表失败:", err3)
		return err3
	}
	return nil
}
